package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.FocusUser;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author SunSun
 * @date 2021/11/1
 */
@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;
    @Override
    public String save(Video video) {
        video.setVid(idWorker.getNextId("video"));
        video.setCreated(System.currentTimeMillis());
        mongoTemplate.save(video);
        return video.getId().toHexString();
    }


    @Override
    public List<Video> findVideos(List<Long> vids) {
        Criteria criteria=Criteria.where("vid").in(vids);
        return mongoTemplate.find(Query.query(criteria),Video.class);
    }

    /**
     * 查询数据库的视频
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Video> queryVideosList(int page, Integer pagesize) {
        Query query=new Query().skip((page-1)*page).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,Video.class);
    }

    @Override
    public void saveFocusUser(FocusUser focusUser) {
        mongoTemplate.save(focusUser);
    }

    @Override
    public void deleteFollowUser(Long userId, Long followUserId) {
        Query query=Query.query(Criteria.where("userId").is(userId)
                .and("followUserId").is(followUserId));
        mongoTemplate.remove(query,FocusUser.class);
    }

    /**
     * 查存userId的视频列表
     * @param page
     * @param pagesize
     * @param uid
     * @return
     */
    @Override
    public PageResult finByUserId(Integer page, Integer pagesize, Long uid) {
        Query query=Query.query(Criteria.where("userId").is(uid));
        long count = mongoTemplate.count(query, Video.class);
        query.limit(pagesize).skip((page-1)*pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Video> videos = mongoTemplate.find(query, Video.class);
        return new PageResult(page,pagesize,count,videos);
    }

}
